<template>
  <main-content title="异常订单">
    <template #tab-bar>
      <div class="tips">提货失败或待发货请求失败的订单会进入异常订单，可尝试重新发起提货</div>
      <!-- <el-radio-group v-model="currentFilter" @change="handleFilterChange">
        <el-radio-button plain :label="item.value" v-for="(item, index) in mallFilterList" :key="index">{{ item.label
        }}（{{ item.count }}）
        </el-radio-button>
      </el-radio-group> -->
    </template>

    <template #search-bar>
      <search-bar inline>
        <template #normal>
          <el-form-item label="订单编号">
            <el-input v-model="form.orderNo" placeholder="订单编号" />
          </el-form-item>

          <el-form-item label="手机号">
            <el-input v-model="form.userPhone" placeholder="手机号码" />
          </el-form-item>
          <el-form-item label="下单时间">
            <el-date-picker v-model="orderTime" type="datetimerange" start-placeholder="开始时间" end-placeholder="结束时间"
              :default-time="defaultTime1" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSearch">查询</el-button>

            <!-- TODO 加权限 -->
            <el-button type="primary" @click="showExportData = true">导出</el-button>
            <el-button type="primary" @click="retryPickUpBatch">批量提货</el-button>
          </el-form-item>

          <!--          <ins-cascader-filter v-model:selected="queryInsIds"></ins-cascader-filter>-->
        </template>
      </search-bar>
    </template>

    <layout-table ref="tokensManage" url="/extensions/merchant/order/pageOrder" :setSearch="setSearch" disable-auto-height
      :param="{ ...form, excHandleStatus: excHandleStatus }" @selection-change="handleSelectionChange" :rowKey="(row: any) => {
        return String(row.id);
      }
        ">
      <el-table-column type="selection" :reserve-selection="true" width="55" />
      <el-table-column prop="createTime" label="创建时间" width="180">
        <template #default="scope">
          {{ formatTime(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="orderNo" label="订单编号" width="180" />
      <el-table-column prop="userPhone" label="用户手机号" width="180" />
      <el-table-column prop="title" label="商品名称" min-width="200" />
      <el-table-column prop="productName" label="规格名称" min-width="200" />
      <el-table-column prop="goodsType" label="商品类型" width="120">
        <template #default="scope">
          {{ getProductType(scope.row.goodsType) }}
        </template>
      </el-table-column>

      <el-table-column label="操作" fixed="right" width="180">
        <template #default="scope">
          <el-button type="primary" link @click="showDialog('retryPickUp', scope.row)" v-has="['08040201']">
            重新提货
          </el-button>
          <el-button type="primary" link @click="closeOrder(scope.row)" v-has="['08040202']">
            关闭并退款
          </el-button>
          <el-button link type="primary" v-has="['08040101']"
            @click="$router.push(`/mall/order/list/orderdetail?id=${scope.row.id}`)">
            查看订单
          </el-button>
        </template>
      </el-table-column>
    </layout-table>
    <exportData v-model:show-dialog="showExportData" :search-data="form" title="异常订单-商城" export-type="abnormlOrderExport">
    </exportData>
  </main-content>

  <!--    重新发货-->
  <set-user-account v-model:show="dialogVisible.retryPickUp" :row-data="currentOperateRow">
  </set-user-account>

  <el-dialog title="批量提货结果" v-model="isResultDialog" width="300px" :before-close="() => isResultDialog = false">
    <div class="uploadExcel">
      <div class="resultTips" style="text-align: center;">
        <el-result icon="error" v-if="result.fail"></el-result>
        <el-result icon="success" v-else></el-result>
        <span>
          导入成功<span class="success">{{ result.success || 0 }}</span>条</span>
        <span>
          导入失败<span class="fail" style="color: #ff3b30;">{{ result.fail || 0 }}</span>条
        </span>
        <div> <el-button type="primary" link @click.stop="downloadRecord">下载失败记录</el-button></div>
      </div>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="isResultDialog = false">完成</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script lang="ts">
export default {
  name: "MallOrderAbnormal",
};
</script>
<script lang="ts" setup>
import { merchantProductTypes } from "@/config/dictionary";
import { getRecentWeekTime } from "@/utils/getRecentWeekTime";
import { WritableComputedRef } from "vue";
import moment from "moment";
import { abnormalOrderStatus } from "@/config/dictionary";
import { IOrderPageRow } from "@/api/modules/order";
import { getAbnormalStatics, retryPickUp, setPickup } from "@/api/order";
import { batchRetryPickUp, getBatchRetryPickUpResult, refundOrder } from "@/api/pointsMall";
import { useGetAbnormalOrderStatus } from "@/views/order/compositions/useGetAbnormalOrderStatus";
import SetUserAccount from "@/views/order/components/SetUserAccount.vue";
import { useMallConfig } from "@/views/pointsMall/compositions/useMallConfig";
import exportData from "@/components/exportData/exportData.vue";
const router = useRouter();
const store = useStore();
const { mallConfig } = useMallConfig();
const { getAbnormalOrderStatusLabel } = useGetAbnormalOrderStatus();
const tokensManage = ref()


const setSearch = ref(0);
const showExportData = ref(false);
const currentFilter = ref(-1);
const mallFilterList = ref(JSON.parse(JSON.stringify(abnormalOrderStatus)));
const orderTime = ref("" as any);
//添加默认一周下单时间
orderTime.value = [getRecentWeekTime().startTime, getRecentWeekTime().endTime]
const form = reactive({
  orderNo: "",
  userPhone: "",
  queryInsIds: <number[]>[],
  serveType: "reissue",
  businessType: "mall",
  businessId: mallConfig.value.id,
  createStartTime: getRecentWeekTime().startTime,
  createEndTime: getRecentWeekTime().endTime,
  withExtOrder: true
});
const excHandleStatus = ref(currentFilter.value)

watch(form, () => {
  getOrderStaticsList()
})

const defaultTime1 = reactive([
  new Date(2000, 1, 1, 0, 0, 0),
  new Date(2000, 2, 1, 23, 59, 59),
]); // '12:00:00', '08:00:00'

watch(orderTime, (val) => {
  /* ... */
  if (val) {
    form.createStartTime = String(new Date(val[0]).getTime());
    form.createEndTime = String(new Date(val[1]).getTime());
  } else {
    form.createStartTime = "";
    form.createEndTime = "";
  }
});
const getProductType = (_productType: number) => {
  return (
    merchantProductTypes.find((item) => item.value == String(_productType))
      ?.label ?? _productType
  );
};

const queryInsIds: WritableComputedRef<number[]> = computed({
  get() {
    return form.queryInsIds;
  },
  set(newValue) {
    form.queryInsIds = newValue;
  },
});

const currentOperateRow = ref({} as IOrderPageRow);
const dialogVisible = reactive({
  retryPickUp: false,
});

const closeOrder = async (row: any) => {
  ElMessageBox.confirm(`确认关闭并退款此订单吗？`, "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    const res = await refundOrder({
      orderId: row.id,
      userId: row.userId,
      remark: '申请退款'
    })
    if (res.code == 200) {
      ElMessage.success("退款成功");
      onSearch()
    }
  });
}
const showDialog = (type: string, row?: IOrderPageRow) => {
  if (['recharge'].includes(row.goodsType)) {
    dialogVisible[type] = true;
  } else {
    resend(row)
  }
  currentOperateRow.value = row
};

const handleFilterChange = (radioValue: any) => {
  excHandleStatus.value = radioValue;
};

const formatTime = (value: string) => {
  if (value) {
    return moment(value).format("YYYY.MM.DD HH:mm:ss");
  }
};

// 获取异常订单
const getOrderStaticsList = async () => {
  mallFilterList.value.forEach(i => i.count = 0)
  const rs = await getAbnormalStatics({
    ...form,
    businessType: "mall",
    businessId: mallConfig.value.id,
  });
  if (rs.code === 200) {
    (rs.payload ?? []).forEach(
      (item: { count: number; excHandleStatus: number }) => {
        mallFilterList.value.forEach((el) => {
          if (item.excHandleStatus === el.value) {
            el.count = item.count;
          }
        });
      }
    );
  }
};

const onSearch = () => {
  setSearch.value++;
};

// 重新发货
const resend = async (row: IOrderPageRow) => {
  const rs = await retryPickUp({ id: row.id });
  if (rs.code === 200) {
    ElMessage.success("请求成功");
  }
};

// 设为未提货
const changeStatusToUnreceived = async (row: IOrderPageRow) => {
  const userId = store.state.user.userId;
  const rs = await setPickup({ orderId: row.id, userId });
  if (rs.code === 200) {
    ElMessage.success("请求成功");
  }
};
const isResultDialog = ref(false)
const selections = ref([])
const handleSelectionChange = (val: any) => { selections.value = val }
const retryPickUpBatch = async () => {
  if (!selections.value.length) {
    return ElMessage.warning('至少选择一条数据！')
  }
  const ids = selections.value.map(i => i.id)
  const res = await batchRetryPickUp({ ids: ids })
  if (res.code == 200) {
    if (res.payload?.token) {
      getBatchResult(res.payload.token)
      tokensManage.value.clearSelection()
    }
  }
}

//获取批量结果
let timer = ref(null)
//记录请求次数
const timerCount = ref(0)
const result = ref({
  fail: 0,
  success: 0
})
const getBatchResult = async (token: string) => {
  const rs = await getBatchRetryPickUpResult({ token: token })

  if (rs.code == 200) {
    clearTimeout(timer.value)
    timer.value = null
    if (rs.payload && rs.payload.processResult == 'success') {
      timerCount.value = 0
      onSearch()
      // ElMessage.success('批量操作完成！')
      isResultDialog.value = true
      result.value.fail = rs.payload.fail
      result.value.success = rs.payload.success
      if (rs.payload.failUrl) {
        result.value.failUrl = rs.payload.failUrl
      }

    } else {
      timerCount.value++
      clearTimeout(timer.value)
      timer.value = setTimeout(() => {
        if (timerCount.value > 30) {
          timerCount.value = 0
          clearTimeout(timer.value)
        } else {
          getBatchResult(token)
        }
      }, 1000)
    }
  } else {
    timerCount.value = 0
    clearTimeout(timer.value)
    timer.value = null
  }
}

const downloadRecord = () => {
  if (result.value.failUrl) {
    let a = document.createElement("a");
    a.setAttribute("href", result.value.failUrl);
    a.setAttribute("download", '失败详情');
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
  }
}

// 监听机构
const insId = computed(() => {
  return store.state.insId.insId;
});
watch(
  () => insId,
  () => {
    getOrderStaticsList();
  },
  {
    deep: true,
  }
);
onMounted(() => {
  console.log("异常订单-积分商城");
  getOrderStaticsList();
});

//清除定时相关数据
onBeforeUnmount(() => {
  timerCount.value = 0
  clearTimeout(timer.value)
  timer.value = null
})
</script>

<style lang="scss" scoped>
.tips {
  display: inline-block;
  border: solid 1px var(--el-color-primary);
  color: var(--el-color-primary);
  background: rgba(0, 30, 112, 0.04);
  font-size: 14px;
  padding: 10px;
  border-radius: 4px;
}
</style>
